package com.yichen.ycOJ.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yichen.ycOJ.common.ErrorCode;
import com.yichen.ycOJ.constant.CommonConstant;
import com.yichen.ycOJ.exception.BusinessException;
import com.yichen.ycOJ.mapper.QuestionSubmitMapper;
import com.yichen.ycOJ.model.dto.questionSubmit.QuestionSubmitAddRequest;
import com.yichen.ycOJ.model.dto.questionSubmit.QuestionSubmitQueryRequest;
import com.yichen.ycOJ.model.entity.Question;
import com.yichen.ycOJ.model.entity.QuestionSubmit;
import com.yichen.ycOJ.model.entity.User;
import com.yichen.ycOJ.model.enums.QuestionSubmitLanguageEnum;
import com.yichen.ycOJ.model.enums.QuestionSubmitStatusEnum;
import com.yichen.ycOJ.model.vo.QuestionSubmitVO;
import com.yichen.ycOJ.model.vo.QuestionVO;
import com.yichen.ycOJ.model.vo.UserVO;
import com.yichen.ycOJ.service.JudgeService;
import com.yichen.ycOJ.service.QuestionService;
import com.yichen.ycOJ.service.QuestionSubmitService;
import com.yichen.ycOJ.service.UserService;
import com.yichen.ycOJ.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;


@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;
    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 题目提交 本地
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return
     */
    @Override
    public Long doQuestionSubmitNative(QuestionSubmitAddRequest questionSubmitAddRequest, HttpServletRequest request) {
        Question question = questionService.getById(questionSubmitAddRequest.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 1. 校验编程语言是否合理
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }

        // todo：可以对用户的提交做一个限制
        User loginUser = userService.getLoginUser(request);
        // 2. 存入提交表
        QuestionSubmit questionSub = new QuestionSubmit();
        questionSub.setQuestionId(questionSubmitAddRequest.getQuestionId());
        questionSub.setCode(questionSubmitAddRequest.getCode());
        questionSub.setUserId(loginUser.getId());
        questionSub.setLanguage(language);
        // 2.1 设置初始状态
        questionSub.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSub.setJudgeInfo("{}");
        boolean save = this.save(questionSub);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交失败");
        }

        // 3. 进行判题逻辑
        CompletableFuture.runAsync(() -> {
            judgeService.doJudge(question.getId(), loginUser);
        });
        return questionSub.getId();
    }

    /**
     * 题目提交 远程
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmitRemote(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionSubmitAddRequest.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //校验编程语言是否合理
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }

        // 是否已提交
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSub = new QuestionSubmit();
        questionSub.setQuestionId(questionSubmitAddRequest.getQuestionId());
        questionSub.setCode(questionSubmitAddRequest.getCode());
        questionSub.setUserId(userId);
        questionSub.setLanguage(language);
        // 设置初始状态
        questionSub.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSub.setJudgeInfo("{}");
        boolean save = this.save(questionSub);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交失败");
            // 提交失败，回滚
        }
        return questionSub.getId();
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();


        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(language), "language", language);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    /**
     * 获取QuestionVO
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser, HttpServletRequest request) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交代码
        Long userId = loginUser.getId();
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        UserVO userVO = userService.getUserVO(loginUser);
        Question question = questionService.getById(questionSubmitVO.getQuestionId());
        QuestionVO questionVO = questionService.getQuestionVO(question, request);
        questionSubmitVO.setUserVO(userVO);
        questionSubmitVO.setQuestionVO(questionVO);
        return questionSubmitVO;
    }

    /**
     * 分页脱敏查询
     *
     * @param questionSubmitPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser, HttpServletRequest request) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser, request))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

}




